<div class="bjui-pageContent">
    <div style="padding:20px;">
        <div class="clearfix">
            <div style="float:left; width:350px; height:100%; overflow:auto;">
                <ul id="menuTree" class="ztree" data-toggle="ztree" 
                    data-options="{
                        expandAll: false,
                        onClick: 'ZtreeClick',
                        nodes:'returnMenuTree'
                    }"
                >
                </ul>
            </div>
            <div id="ztree-detail" style="margin-left:350px; width:500px; height:400px;">
                <div class="bs-example" data-content="详细信息">
                    <div class="form-group">
                        <label for="j_menu_name" class="control-label x85">菜单名称：</label>
                        <input type="text" class="form-control validate[required] required" name="m.name" id="j_menu_name" size="20" placeholder="名称" />
                    </div>
                    <div class="form-group">
                        <label for="j_menu_faicon" class="control-label x85">菜单图标：</label>
                        <input type="text" class="form-control" name="m.faicon" id="j_menu_faicon" size="20" placeholder="faicon" />
                    </div>
                    <div class="form-group">
                        <label for="j_menu_url" class="control-label x85">资源链接：</label>
                        <textarea name="m.url" id="j_menu_url"  cols="40" rows="3"></textarea>
                    </div>
                    <div class="form-group">
                        <label for="j_menu_remark" class="control-label x85">菜单描述：</label>
                        <textarea name="m.remak" id="j_menu_remark"  cols="40" rows="5"></textarea>
                    </div>
                    <!-- 
                    <div class="form-group">
                        <label for="j_menu_tabid" class="control-label x85">tabid：</label>
                        <input type="text" class="form-control" name="m.tabid" id="j_menu_tabid" size="20" placeholder="tabid" />
                    </div>
                     
                    <div class="form-group">
                        <label for="j_menu_target" class="control-label x85">target：</label>
                        <select class="selectpicker show-tick" id="j_menu_target" data-style="btn-default btn-sel" data-width="auto">
                            <option value=""></option>
                            <option value="navTab">navTab</option>
                            <option value="dialog">dialog</option>
                        </select>
                    </div>
                    -->
                    <div class="form-group" style="padding-top:8px; border-top:1px #DDD solid;">
                        <label class="control-label x85"></label>
                        <button class="btn btn-green" onclick="M_Ts_Menu();">更新菜单</button>
                        <div style="margin-top:8px;">
                        <i class="fa fa-warning" style="color:red"></i> 
                        	注意：<br>
                        	1、右键菜单树进行添加/删除前，请先选择要操作的节点。<br>
                        	2、不能删除拥有子菜单的菜单。
                        	  
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- 
        <hr>
        <div class="btn-group" style="margin-top:5px;">
            <button type="button" class="btn-default btn-sm" onclick="changeZtree(1);">默认编/删按钮</button>
            <button type="button" class="btn-default btn-sm" onclick="changeZtree(2);">自定义添/删按钮</button>
            <button type="button" class="btn-default btn-sm" onclick="changeZtree(3);">复选框</button>
            <button type="button" class="btn-default btn-sm" onclick="changeZtree(4);">拖拽</button>
            <button type="button" class="btn-default btn-sm" onclick="changeZtree(5);">删除</button>
            <button type="button" class="btn-default btn-sm" onclick="changeZtree(6);">自定义DOM</button>
            <button type="button" class="btn-orange btn-sm" style="float: right;" onclick="changeZtree(7);">提交树</button>
        </div>
         -->
    </div>
</div>
<!-- 菜单管理 -->
<script type="text/javascript">
function changeZtree(t) {
    var $panel = $.CurrentNavtab;
    var $t     = $('#menuTree'),
        $span  = $('#ztree-'+ t),
        $log   = $('#ztree-log'),
        op     = $t.data()
    
    if (t != 7)
        $.fn.zTree.destroy('menuTree')
    
    switch(t) {
        case 1:
            var edit   = op.showRenameBtn ? false : true,
                rename = op.showRenameBtn ? false : true,
                remove = op.showRemoveBtn ? false : true
            $t.data('editEnable', edit).data('showRenameBtn', rename).data('showRemoveBtn', remove)
            
            break
        case 2:
            var add    = op.addHoverDom ? null : 'edit',
                remove = op.removeHoverDom ? null : 'edit'
            
            $t.data('addHoverDom', add).data('removeHoverDom', remove)
            break
        case 3:
            var check = op.checkEnable ? false : true
            
            $t.data('checkEnable', check)
            
            break
        case 4:
            var edit   = op.editEnable ? true : true,
                bDrag  = op.beforeDrag ? '' : 'M_BeforeNodeDrag',
                bDrop  = op.beforeDrop ? '' : 'M_BeforeNodeDrop',
                onDrop = op.onDrop ? '' : 'M_NodeDrop'
            
            $t.data('editEnable', edit).data('beforeDrag', bDrag).data('beforeDrop', bDrop).data('onDrop', onDrop)
            
            break
        case 5:
            var add    = op.beforeRemove ? null : 'edit',
                remove = op.beforeRemove ? null : 'edit',
                bR     = op.beforeRemove ? null : 'M_BeforeRemove'
                oR     = op.onRemove ? null : 'M_NodeRemove'
            
            $t.data('addHoverDom', add).data('removeHoverDom', remove).data('beforeRemove', bR).data('onRemove', oR)
            break
        case 6:
            var diy = op.addDiyDom ? null : 'M_AddDiyDom'
            
            $t.data('addDiyDom', diy)
            
            break
        case 7:
            var tree = $.fn.zTree.getZTreeObj("menuTree")
            var menus = tree.getNodes()
            //$log.val(JSON.stringify(menus))
            break
    }
    $panel.initui()
}
//单击事件
function ZtreeClick(event, treeId, treeNode) {
    event.preventDefault()
    var $detail = $('#ztree-detail')
    if ($detail.attr('tid') == treeNode.tId) return
	if (treeNode.name) $('#j_menu_name').val(treeNode.name)
	if (treeNode.url) {
		$('#j_menu_url').val(treeNode.url)
	} else {
		$('#j_menu_url').val('')
	}
	if (treeNode.faicon) {
		$('#j_menu_faicon').val(treeNode.faicon)
	} else {
		$('#j_menu_faicon').val('')
	}
	if (treeNode.remark) {
		$('#j_menu_remark').val(treeNode.remark)
	} else {
		$('#j_menu_remark').val('')
	}
	/**
	if (treeNode.target) {
		$('#j_menu_target').selectpicker('val', treeNode.target)
	} else {
		$('#j_menu_target').selectpicker('val', '')
	}
	**/
	$detail.attr('tid', treeNode.tId)
    $detail.show()
}
//保存属性
function M_Ts_Menu() {
	var zTree  = $.fn.zTree.getZTreeObj("menuTree")
	var upNode = zTree.getSelectedNodes()[0]
	
	if (!upNode) {
		$(this).alertmsg('warn', '未选中任何菜单！')
        return
	}
	var name   = $('#j_menu_name').val()
	var faicon  = $('#j_menu_faicon').val()
	var url    = $('#j_menu_url').val()
	var remark = $('#j_menu_remark').val()
	
	if ($.trim(name).length == 0) {
		$(this).alertmsg('warn', '菜单名称不能为空！')
		return;
	}
	
	upNode.name   = name;
	upNode.url    = url;
	upNode.faicon  = faicon;
	upNode.remark = remark;
	var menuInfo = {};
	menuInfo.id = upNode.id;
	menuInfo.name   = name;
	menuInfo.url    = url;
	menuInfo.faicon  = faicon;
	menuInfo.remark = remark;
	menuInfo.pId = upNode.pId;
	//向后台发送保存操作
	$.ajax({
		url:"sys/res/menuMgr",
		type:"post",
		dataType:"json",
		data:{action:'saveMenu',menuInfo:JSON.stringify(menuInfo)},
		success:function(e){
			if(e&&e.success){
				$(this).alertmsg('info', '保存成功！')
				upNode.id = e.msg;
				alert(upNode.id);
				zTree.updateNode(upNode);
			}else{
				$(this).alertmsg('warn', e ? e.msg :'保存失败，请检查菜单各值格式是否正确！')	
			}
			
		},
		async:false
	});
}
//
function M_BeforeNodeDrag(treeId, treeNodes) {
    //var $log = $('#ztree-log');
    //$log.val('开始拖拽：'+ treeNodes[0].name +'！\n'+ $log.val());
    return true;
}
//监听拖拽事件
function M_BeforeNodeDrop(treeId, treeNodes, targetNode, moveType, isCopy) {
    /*禁止插入层级为2的节点*/
    if (moveType == 'inner' && targetNode.level == 2) {
        return false;
    }
    /*禁止插入剩余层级不足的子节点*/
    if (moveType == 'inner' && treeNodes[0].isParent) {
        var molevel = 2 - targetNode.level //剩余层级
        var maxlevel = 1
        var zTree = $.fn.zTree.getZTreeObj("menuTree")
        var nodes = zTree.transformToArray(treeNodes)
        var level = nodes[0].level
        
        for (var i = 1; i < nodes.length; i++) {
            if (nodes[i].level == (level + 1)) {
                maxlevel++
                level++
            }
        }
        if (maxlevel > molevel) {
            return false
        }
    }
    return true
}
//拖拽结束事件
function M_NodeDrop(event, treeId, treeNodes, targetNode, moveType, isCopy) {
    //var $log = $('#ztree-log')
    //$log.val('拖拽结束！\n'+ $log.val())
    if(moveType=='inner' || moveType=='prev' || moveType=='next'){
    	if(treeNodes[0].id==undefined)return;
    	// inner 更父节点，并且变为最后一个节点
    	// prev 成为同级前一个节点，去其下一个序号的节点id
    	// next 成为同级后一个节点，去其上一个序号的节点id
    	//向后台发送请求
    	$.ajax({
    		url:"sys/res/menuMgr",
    		type:"post",
    		dataType:"json",
    		data:{action:'moveMenu',moveType:moveType,moveId:treeNodes[0].id,targetId:targetNode.id},
    		success:function(r){
    			if(r.success==false){
    				$(this).alertmsg('warn', '菜单移动出错，请联系管理员处理！')
    			}
    		},
    		async:false
    	});
    }
}
//删除前事件
function M_BeforeRemove(treeId, treeNode) {
    //var $log = $('#ztree-log')
    //$log.val('准备删除：'+ treeNode.name +'！\n'+ $log.val())
    return true
}
//删除结束事件
function M_NodeRemove(event, treeId, treeNode) {
    //var $log = $('#ztree-log')
    //$log.val('删除成功！\n'+ $log.val())
}
//自定义DOM
function M_AddDiyDom(treeId, treeNode) {
    var aObj = $('#' + treeNode.tId + '_a')
	if ($('#diyBtn_'+ treeNode.id).length > 0) return
	$('#diyBtn_'+ treeNode.id).bind('click', function() {$(this).alertmsg('info', (treeNode.name +' 的飞机！'))})
}
//获取菜单树
function returnMenuTree() {
	var data;
	$.ajax({
		url:"sys/res/menuMgr",
		type:"post",
		dataType:"json",
		data:{action:'menuTree'},
		success:function(e){
			data=e;
		},
		async:false
	});
    //return [{"id":1,"pid":0,"faicon":"rss","faiconClose":"cab","name":"表单元素","level":0,"tId":"menuTree_1","parentTId":null,"open":false,"isParent":false,"zAsync":true,"isFirstNode":true,"isLastNode":false,"isAjaxing":false,"checked":false,"checkedOld":false,"nocheck":false,"chkDisabled":false,"halfCheck":false,"check_Child_State":-1,"check_Focus":false,"isHover":false,"editNameFlag":false},{"id":10,"pid":1,"url":"form-button.html","tabid":"form-button","faicon":"bell","pId":1,"name":"按钮","level":0,"tId":"menuTree_2","parentTId":null,"open":false,"isParent":false,"zAsync":true,"isFirstNode":false,"isLastNode":false,"isAjaxing":false,"checked":false,"checkedOld":false,"nocheck":false,"chkDisabled":false,"halfCheck":false,"check_Child_State":-1,"check_Focus":false,"isHover":false,"editNameFlag":false},{"id":11,"pid":1,"url":"form-input.html","tabid":"form-input","faicon":"info-circle","pId":1,"name":"文本框","level":0,"tId":"menuTree_3","parentTId":null,"open":false,"isParent":false,"zAsync":true,"isFirstNode":false,"isLastNode":false,"isAjaxing":false,"checked":false,"checkedOld":false,"nocheck":false,"chkDisabled":false,"halfCheck":false,"check_Child_State":-1,"check_Focus":false,"isHover":false,"editNameFlag":false},{"id":12,"pid":1,"url":"form-select.html","tabid":"form-select","faicon":"ellipsis-v","pId":1,"name":"下拉选择框","level":0,"tId":"menuTree_4","parentTId":null,"open":false,"isParent":false,"zAsync":true,"isFirstNode":false,"isLastNode":false,"isAjaxing":false,"checked":false,"checkedOld":false,"nocheck":false,"chkDisabled":false,"halfCheck":false,"check_Child_State":-1,"check_Focus":false,"isHover":false,"editNameFlag":false},{"id":13,"pid":1,"url":"form-checkbox.html","tabid":"table","faicon":"soccer-ball-o","pId":1,"name":"复选、单选框","level":0,"tId":"menuTree_5","parentTId":null,"open":false,"isParent":false,"zAsync":true,"isFirstNode":false,"isLastNode":false,"isAjaxing":false,"checked":false,"checkedOld":false,"nocheck":false,"chkDisabled":false,"halfCheck":false,"check_Child_State":-1,"check_Focus":false,"isHover":false,"editNameFlag":false},{"id":14,"pid":1,"url":"form.html","tabid":"form","faicon":"comments","pId":1,"name":"表单综合演示","level":0,"tId":"menuTree_6","parentTId":null,"open":false,"isParent":false,"zAsync":true,"isFirstNode":false,"isLastNode":false,"isAjaxing":false,"checked":false,"checkedOld":false,"nocheck":false,"chkDisabled":false,"halfCheck":false,"check_Child_State":-1,"check_Focus":false,"isHover":false,"editNameFlag":false},{"id":2,"pid":0,"name":"表格","level":0,"tId":"menuTree_7","parentTId":null,"open":false,"isParent":false,"zAsync":true,"isFirstNode":false,"isLastNode":false,"isAjaxing":false,"checked":false,"checkedOld":false,"nocheck":false,"chkDisabled":false,"halfCheck":false,"check_Child_State":-1,"check_Focus":false,"isHover":false,"editNameFlag":false},{"id":20,"pid":2,"url":"table.html","tabid":"table","faicon":"signal","pId":2,"name":"普通表格","level":0,"tId":"menuTree_8","parentTId":null,"open":false,"isParent":false,"zAsync":true,"isFirstNode":false,"isLastNode":false,"isAjaxing":false,"checked":false,"checkedOld":false,"nocheck":false,"chkDisabled":false,"halfCheck":false,"check_Child_State":-1,"check_Focus":false,"isHover":false,"editNameFlag":false},{"id":21,"pid":2,"url":"table-fixed.html","tabid":"table-fixed","faicon":"rss-square","pId":2,"name":"固定表头表格","level":0,"tId":"menuTree_9","parentTId":null,"open":false,"isParent":false,"zAsync":true,"isFirstNode":false,"isLastNode":false,"isAjaxing":false,"checked":false,"checkedOld":false,"nocheck":false,"chkDisabled":false,"halfCheck":false,"check_Child_State":-1,"check_Focus":false,"isHover":false,"editNameFlag":false},{"id":22,"pid":2,"url":"table-edit.html","tabid":"table-edit","faicon":"bookmark-o","pId":2,"name":"可编辑表格","level":0,"tId":"menuTree_10","parentTId":null,"open":false,"isParent":false,"zAsync":true,"isFirstNode":false,"isLastNode":true,"isAjaxing":false,"checked":false,"checkedOld":false,"nocheck":false,"chkDisabled":false,"halfCheck":false,"check_Child_State":-1,"check_Focus":false,"isHover":false,"editNameFlag":false}]
    return data;
}
//树捕获鼠标右键
function zTreeOnRightClick(event, treeId, treeNode) {
    alert(treeNode ? treeNode.tId + ", " + treeNode.name : "isRoot");
};

//修改树编辑状态
//changeZtree(2);//添加新增删除按钮
changeZtree(4);//允许拖动
//changeZtree(3);//复选框
//添加右键菜单属性
$('#menuTree').contextmenu('show', 
  {
      items:[
         {
             icon  : 'plus',
             title : '新增子菜单',
             func  : function(parent, menu) {
            	 //获取选择的菜单对象
            	 var zTree = $.fn.zTree.getZTreeObj("menuTree");
            	 var node = zTree.getSelectedNodes()[0];
            	 if(node){
            		 //添加节点到菜单树上
            		 var new_node = {name:node.name+"_子菜单",pId:node.id};
            		 new_node = zTree.addNodes(node,new_node,false);
            		 //修改新增节点信息
            		 var new_node = zTree.getNodeByTId(targetNode.tId);
            		 // TODO 向后台发送服务保存改节点
					            		 
            	 }else{
            		 $(this).alertmsg('warn', '请选择要操作的菜单节点');
            	 }
             }
         },
         {
             icon  : 'remove',
             title : '删除菜单',
             func  : function(parent, menu) {
            	 //获取选择的菜单对象
            	 var zTree = $.fn.zTree.getZTreeObj("menuTree");
            	 var node = zTree.getSelectedNodes()[0];
            	 if(node){
	            	 $(this).alertmsg('confirm', '是否删除菜单（包含子菜单）--'+node.name, {okCall:function(){
	            		 var r = ajaxJsonSync("sys/res/menuMgr",{action:'delMenu',menuId:node.id});
	            		 if(r.success){
	            			 //从树上删除节点
	            			 zTree.removeNode(node);
	            		 }
	            		 //输出提示信息
	            		 actionResultTip(r);
	            	 },title:"确认删除菜单？"});
            	 }else{
            		 $(this).alertmsg('warn', '请选择要操作的菜单节点');
            	 }
             }
         }
     ]
  }
);
</script>